class PartStockin < ActiveRecord::Base
	belongs_to :user
	has_many :part_stockin_details

  enum status: %w(新建 已审核)


	after_create :gen_code

	def gen_code
	  code = rand(100000).to_s.rjust(6, "0")
  	  update_attributes(code: code)
	end

	def add_inventory
      self.part_stockin_details.each do |p|
        qty = p.qty
        amount = p.sub_total
        inventory = Inventory.find_by_part_id(p.part_id)
        if inventory.nil?
          Inventory.create(part_id: p.part_id, qty: qty, amount: amount)
        else
          inventory.update(qty: inventory.qty+qty, amount: inventory.amount+amount)
        end
      end
	end
end
